package showtime.framework.utils
{
	import flash.utils.ByteArray;
	
	/** 
	 * @project showtime
	 * @author yinhao
	 * @date 2011-5-24
	 *
	 */
	
	public class NumberUtility
	{
		public function NumberUtility()
		{
		}
		
		static public function toBase16(input:ByteArray):String
		{
			var output:String = new String();
			const hex:String = "0123456789abcdef";
			const length:int = input.length;
			for(var i:int = 0; i < length; i++) {
				output += hex.charAt((input[i] & 0xF0) >> 4);
				output += hex.charAt(input[i] & 0x0F);
			}
			return output;
		}
		
		static public function fromBase16(input:String):ByteArray
		{
			var output:ByteArray = new ByteArray();
			const hex:Object = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'a':10,'b':11,'c':12,'d':13,'e':14,'f':15,'A':10,'B':11,'C':12,'D':13,'E':14,'F':15};
			const length:int = input.length;
			var i:int = 0;
			while(i < length) {
				var byte:uint = (hex[input.charAt(i)] << 4);
				i++;
				if(i < length) {
					byte += hex[input.charAt(i)];
					i++;
				}
				output.writeByte(byte); 
			}
			return output;
		}
		
		static public function getRate(probability:Number):Boolean
		{
			var seed:Number = Math.random() * (100 * 1000 + 1);
			
			if (seed <= probability)
			{
				return true;
			}
			return false;
		}
		
		/**
		 * Generates a random number. NOTO: To create a series of predictable
		 * random numbers, add the random numnber you generate each time
		 *  
		 * @param bean
		 * @return 
		 * 
		 */		
		static public function getUnequalRandom(seed:Number = NaN):int
		{
			if(isNaN(seed))
			{
				return Math.random();
			}
			
			var seedOne:int = Math.random() * seed;
			var seedTwo:int = Math.random() * seed;
			
			return seedOne < seedTwo ? seedOne : seedTwo;
		}
		/**
		 * Generates a random number.  NOTE: To create a series of predictable
		 * random numbers, add the random number you generate each time
		 * to the <code>Seed</code> value before calling <code>getEqualRandom()</code> again.
		 * 
		 * @param	Seed	A user-provided value used to calculate a predictable random number.
		 * 
		 * @return	A <code>Number</code> between 0 and 1.
		 */
		static public function getEqualRandom(seed:Number = NaN):Number
		{
			if(isNaN(seed))
			{
				return Math.random();
			}			
			else
			{
				//Make sure the seed value is OK
				if(seed == 0)
				{
					seed = Number.MIN_VALUE;
				}
				
				if(seed >= 1)
				{
					if((seed % 1) == 0)
					{
						seed /= Math.PI;
					}
					
					seed %= 1;
				}
				else if(seed < 0)
				{
					seed = (seed % 1) + 1;
				}

				
				//Then do an LCG thing and return a predictable random number
				return ((69621 * int(seed * 0x7FFFFFFF)) % 0x7FFFFFFF) / 0x7FFFFFFF;
			}
		}
	}
}